package com.talent.service.iot.mqtt.codec.decoder;

import com.talent.service.iot.mqtt.model.entity.TlTopic;
import com.talent.service.iot.mqtt.model.fix.TlMqttFixedHead;
import com.talent.service.iot.mqtt.model.payload.TlMqttUnSubscribePayload;
import com.talent.service.iot.mqtt.model.request.TlMqttUnSubscribeReq;
import com.talent.service.iot.mqtt.model.variable.TlMqttUnSubscribeVariableHead;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.mqtt.MqttMessageType;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName：TlConnectDecoder
 * @Author: hszhou
 * @Date: 2024/11/30 15:12
 * @Description: 订阅确定解码器
 */
@Component
public class TlMqttUnSubscribeDecoder {

    public TlMqttUnSubscribeReq build(ByteBuf buf,  int remainingLength){
        TlMqttFixedHead fixedHead = decodeFixedHeader(remainingLength);
        TlMqttUnSubscribeVariableHead variableHead = decodeVariableHeader(buf);
        TlMqttUnSubscribePayload payload = decodePayLoad(buf);
        return new TlMqttUnSubscribeReq(fixedHead,variableHead,payload);
    }


    TlMqttFixedHead decodeFixedHeader(int remainingLength) {
        TlMqttFixedHead fixedHead =new TlMqttFixedHead();
        fixedHead.setMessageType(MqttMessageType.UNSUBSCRIBE);
        fixedHead.setLength(remainingLength);
        return fixedHead;
    }


    TlMqttUnSubscribeVariableHead decodeVariableHeader(ByteBuf buf) {
        int messageId = buf.readUnsignedShort();
        TlMqttUnSubscribeVariableHead variableHead = new TlMqttUnSubscribeVariableHead();
        variableHead.setMessageId(messageId);
        return variableHead;
    }


    TlMqttUnSubscribePayload decodePayLoad(ByteBuf buf) {
        TlMqttUnSubscribePayload payload = new TlMqttUnSubscribePayload();
        List<TlTopic> topics = new ArrayList<>();
        StringBuffer sb= new StringBuffer();
        while (buf.readableBytes()!=0){
            TlTopic topic = new TlTopic();
            int topicAFilterLength = buf.readUnsignedShort();
            byte[] topicAFilter=new byte[topicAFilterLength];
            buf.readBytes(topicAFilter);
            String topicAFilterStr = new String(topicAFilter);
            topic.setName(topicAFilterStr);
            topics.add(topic);
            sb.append(topicAFilterStr+" ");
        }
        payload.setTopics(topics);
        return payload;
    }
}
